package Master;

import javax.xml.ws.Dispatch;
import java.util.LinkedList;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Project:    metsysdirg
 * File Name: IO.java
 * Change History:
 *     ********************************
 *     1.0     5/14/2011    Hengfeng Li
 *         Create the skeleton file
 *     ********************************
 *
 */

public class DispatcherQueue {
    private final int nDispatchers;
    private final PoolDispatcher[] dispatchers;
    private final ConcurrentLinkedQueue<TaskRunnable> queue;


    public DispatcherQueue(ArrayList<Resource> resources){
        System.out.println("ArrayList's size" + resources.size());
        this.nDispatchers = resources.size();
        queue = new ConcurrentLinkedQueue<TaskRunnable>();
        dispatchers = new PoolDispatcher[nDispatchers];
        for(int i = 0; i < nDispatchers; i++){
            dispatchers[i] = new PoolDispatcher(resources.get(i));
            dispatchers[i].start();
        }
    }

    public void execute(TaskRunnable task){
        synchronized (queue){
            queue.offer(task);
            queue.notify();
        }
    }

    private class PoolDispatcher extends Thread {
        private Resource resource;

        public PoolDispatcher(Resource resource){
            this.resource = resource;
        }

        public void run(){
            TaskRunnable task;
            while (true) {
                synchronized (queue) {
                    while (queue.isEmpty()){
                        try {
                            queue.wait();
                        }
                        catch (InterruptedException ignored){

                        }
                    }
                    task = (TaskRunnable) queue.poll();
                }

                try{
                    task.specifyResource(resource);
                    task.run();
                } catch (RuntimeException e) {
                    System.out.println("Error happens while dispatcher is running..");
                }
            }
        }
    }
}
